import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync, appoxEnums } from '@/appox/appox'

export const useBusMessageChooserStore = defineStore('busMessageChooser', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const searchKey = ref('')
  const treeData = ref([])
  const originSelectedId = ref(null)

  // 计算属性
  const showDeleteButton = computed(() => originSelectedId.value !== null)

  async function updateTreeData(key) {
    const signalTree = await agencyAsync.getSignalTree()
    if (!signalTree) {
      treeData.value = []
      return
    }

    const topNodes = []
    const keyLower = key.toLowerCase()
    const keyValid = key.length >= 2

    for (const top of signalTree) {
      if (top.type !== appoxEnums.SignalTreeNodeType.BusProtocol) continue
      
      const topMatch = keyValid && top.name.toLowerCase().includes(keyLower)
      const topNode = {
        id: top.id,
        name: top.name,
        children: []
      }
      let shouldAddTopNode = !keyValid || topMatch

      if (top.children) {
        for (const middle of top.children) {
          const middleMatch = keyValid && (middle.id.toLowerCase().includes(keyLower) || middle.name.toLowerCase().includes(keyLower))
          const isSelected = middle.id === originSelectedId.value

          const middleNode = {
            id: middle.id,
            name: middle.name,
            exist: isSelected
          }
          const shouldAddMiddleNode = !keyValid || topMatch || middleMatch

          if (shouldAddMiddleNode) {
            topNode.children.push(middleNode)
            shouldAddTopNode = true
          }
        }
      }

      if (shouldAddTopNode) {
        topNode.expandChildren = keyValid
        topNodes.push(topNode)
      }
    }

    treeData.value = topNodes
  }

  watch(searchKey, (newVal) => {
    const key = newVal ?? ''
    updateTreeData(key)
  })

  // 动作
  function initialize(originMessageId = null) {
    originSelectedId.value = originMessageId
    searchKey.value = ''
    updateTreeData('')
  }


  function confirm(messageNode) {
    const messageId = messageNode ? messageNode.id : null
    dialogQueue.hide(messageId)
  }

  function deleteMessage() {
    dialogQueue.hide(null)
  }

  function cancel() {
    dialogQueue.hide(originSelectedId.value)
  }

  function show(originMessageId = null) {
    return dialogQueue.show({
      onLoaded: () => initialize(originMessageId)
    })
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    searchKey,
    treeData,
    originSelectedId,
    // 计算属性
    showDeleteButton,
    // 动作
    initialize,
    confirm,
    deleteMessage,
    cancel,
    show,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
})
